package 字符串;

/**
 * @Author Weton Li
 * @Date 2021/4/6 18:07
 */
public class 反转字符串2 {


    public static String method(String s, int k) {
        char[] ch = s.toCharArray();
        int n = ch.length;

        for (int i = 0; i < n; i += k * 2) { // 每2k为一部分 反转其半部分
            int left = i;
            int right = (i + k - 1 < n) ? i + k - 1 : n - 1; // 判断下标是否越界 若下标>=n，则右指针指向最后一个字符n-1
            while (left < right) {
                char temp = ch[left];
                ch[left] = ch[right];
                ch[right] = temp;
                left++;
                right--;
            }
        }
        String res = new String(ch);
        return res;
    }

    public static void main(String[] args) {
        String input = "abcdefg"; // bacdfeg
        int inputK = 2;
        System.out.println(method(input, inputK));
    }
}
